//
//  StatusTool.swift
//  微博项目
//
//  Created by admin on 16/3/8.
//  Copyright © 2016年 jin. All rights reserved.
//

import UIKit

class StatusTool: NSObject {
    class func getNewStatus(requestStatusParameter : RequestStatusParameter,progressParameter: ((NSProgress) -> Void)?, successParameter: (([StatusCellFrame]?) -> Void)?, failureParameter: ((NSURLSessionDataTask?, NSError) -> Void)?)
    {
        let manage = AFHTTPSessionManager()
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        var statuses:[StatusCellFrame] = []
        Status.mj_setupObjectClassInArray({ () -> [NSObject : AnyObject]! in
            return ["pic_urls" : Picture.self]
        })
        self.getCache(requestStatusParameter, query: { (queryData) -> (Void) in
            let number = NSNumber(char: 0)
            // 如果在缓存数据库中有数据，则从缓存中读,存在一个bug，当已经有缓存的数据，然后用户有超过10条的未读微博的时候，只会显示最新的失调，可以清理下缓存，以避免这种情况
            
            if queryData.count > 0 && (requestStatusParameter.since_id.compare(number) == NSComparisonResult.OrderedSame || requestStatusParameter.max_id.compare(number) == NSComparisonResult.OrderedSame)
            {
                for var status in queryData
                {
                    statuses.append(StatusCellFrame(status: Status.mj_objectWithKeyValues(status)))
                }
                successParameter!(statuses)
            }
            else
            {
                manage.GET(url, parameters: requestStatusParameter.mj_keyValues(), progress: { (progress:NSProgress) -> Void in
                    progressParameter!(progress)
                    }, success: { (task:NSURLSessionDataTask, data:AnyObject?) -> Void in
                        
                        
                        let statusesData = data?.valueForKey("statuses") as! NSArray
                        self.saveCache(statusesData)
                        print(statusesData.count)
                        for var status in statusesData
                        {
                            statuses.append(StatusCellFrame(status: Status.mj_objectWithKeyValues(status)))
                        }
                        successParameter!(statuses)
                    }) { (task:NSURLSessionDataTask?, error:NSError) -> Void in
                        failureParameter!(task,error)
                }
            }
        })
    }
    // 从缓存中读区数据
    class func getCache(parameter:RequestStatusParameter,query:((queryData:NSMutableArray)->(Void)))
    {
        self.createStatusTabel()
        let sql = "SELECT * FROM status_status WHERE id < ? and id > ?  ORDER BY id DESC  limit ?"
        DBTool.query(sql, withArgumentsInArray: [parameter.max_id,parameter.since_id,parameter.count]) { (result) -> (Void) in
            let arr:NSMutableArray = NSMutableArray()
            if result != nil
            {
                while(result!.next())
                {
                    let dic:NSDictionary = ["id":"\((result?.intForColumn("id"))!)","user_id":(result?.stringForColumn("user_id"))!,"status_content":(result?.dataForColumn("status_content"))!]
                    let data:AnyObject? = try? NSJSONSerialization.JSONObjectWithData((result?.dataForColumn("status_content"))!, options: NSJSONReadingOptions.AllowFragments)
                    arr.addObject(data!)
                }
            }
            query(queryData: arr)
        }
    }
    class func saveCache(statuses:NSArray)
    {
        self.createStatusTabel()
        let sql = "insert INTO status_status VALUES (?,?,?)"
        for var i = 0;i < statuses.count;i++
        {
            let id = (statuses[i] as! NSDictionary).valueForKey("id")
            let userId = Account.shareAccount()?.uid!
            let data = try? NSJSONSerialization.dataWithJSONObject(statuses[i], options: NSJSONWritingOptions.PrettyPrinted)
            DBTool.execute(sql, withArgumentsInArray: [id!,userId!,data!], success: { (bool) -> (Void) in
                print(bool)
            })
        }
    }
    class func createStatusTabel()
    {
        let sql = "CREATE TABLE if NOT EXISTS `status_status`(`id` INT PRIMARY KEY NOT NULL,`user_id` INT NOT NULL,`status_content` blob NOT NULL)"
        DBTool.execute(sql, withArgumentsInArray: nil ,success: nil)
    }
}
